

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/crystal575/img/favicon.png">
  <link rel="icon" href="/crystal575/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="Hello,here is crystal575&#39;s blog.">
  <meta name="author" content="crystal575">
  <meta name="keywords" content="">
  
  <title>golanggolang编程思想 - crystal575&#39;s blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/crystal575/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10.7.2/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/crystal575/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"crystal575.gitee.io","root":"/crystal575/","version":"1.8.11","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/crystal575/js/utils.js" ></script>
  <script  src="/crystal575/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/crystal575/">&nbsp;<strong>crystal575's blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/crystal575/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/crystal575/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/crystal575/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/crystal575/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/crystal575/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/crystal575/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="golanggolang编程思想">
              
            </span>

            
              <div class="mt-3">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-author" aria-hidden="true"></i>
      crystal575
    </span>
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-11-13 17:13" pubdate>
        2021年11月13日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      4.7k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      90
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">golanggolang编程思想</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：2021年11月13日 下午
                
              </p>
            
            <div class="markdown-body">
              <h1>1. 接口</h1>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211101223004741.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211101223004741">
<h2 id="1-1-接口的概念">1.1 接口的概念</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;learngo2/testing&quot;</span><br>)<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getRetriever</span><span class="hljs-params">()</span> <span class="hljs-title">retriever</span></span> &#123;<br>	<span class="hljs-keyword">return</span> testing.Retriever&#123;&#125;<br>&#125;<br><br><span class="hljs-keyword">type</span> retriever <span class="hljs-keyword">interface</span> &#123;<br>	Get(<span class="hljs-keyword">string</span>) <span class="hljs-keyword">string</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	<span class="hljs-keyword">var</span> r retriever= getRetriever()<br>	fmt.Println(r.Get(<span class="hljs-string">&quot;https://www.imooc.com&quot;</span>))<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="1-2-鸭子类型">1.2 鸭子类型</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211101232339956.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211101232339956">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211101232536869.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211101232536869">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211101232734159.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211101232734159">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211101232852784.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211101232852784">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211101233114379.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211101233114379">
<h2 id="1-3-接口的定义和实现">1.3 接口的定义和实现</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211101233214163.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211101233214163">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211101234117743.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211101234117743">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211101234139720.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211101234139720">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// real.go</span><br><span class="hljs-keyword">package</span> <span class="hljs-built_in">real</span><br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;net/http&quot;</span><br>	<span class="hljs-string">&quot;net/http/httputil&quot;</span><br>	<span class="hljs-string">&quot;time&quot;</span><br>)<br><br><span class="hljs-keyword">type</span> Retriever <span class="hljs-keyword">struct</span> &#123;<br>	UserAgent <span class="hljs-keyword">string</span><br>	TimeOut   time.Duration<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r Retriever)</span> <span class="hljs-title">Get</span><span class="hljs-params">(url <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">string</span></span> &#123;<br>	resp, err := http.Get(url)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(err)<br>	&#125;<br><br>	result, err := httputil.DumpResponse(<br>		resp, <span class="hljs-literal">true</span>)<br>	resp.Body.Close()<br><br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(err)<br>	&#125;<br><br>	<span class="hljs-keyword">return</span> <span class="hljs-keyword">string</span>(result)<br>&#125;<br></code></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// mock.go</span><br><span class="hljs-keyword">package</span> mock<br><br><span class="hljs-keyword">type</span> Retriever <span class="hljs-keyword">struct</span> &#123;<br>	Contents <span class="hljs-keyword">string</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r Retriever)</span> <span class="hljs-title">Get</span><span class="hljs-params">(url <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">string</span></span> &#123;<br>	<span class="hljs-keyword">return</span> r.Contents<br>&#125;<br></code></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// main.go</span><br><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;learngo/retriever/mock&quot;</span><br>	<span class="hljs-string">&quot;learngo/retriever/real&quot;</span><br>)<br><br><span class="hljs-keyword">type</span> Retriever <span class="hljs-keyword">interface</span> &#123;<br>	Get(url <span class="hljs-keyword">string</span>) <span class="hljs-keyword">string</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">download</span><span class="hljs-params">(r Retriever)</span> <span class="hljs-title">string</span></span> &#123;<br>	<span class="hljs-keyword">return</span> r.Get(<span class="hljs-string">&quot;http://www.imooc.com&quot;</span>)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	<span class="hljs-keyword">var</span> r Retriever<br>	r = mock.Retriever&#123;<span class="hljs-string">&quot;this is fake imooc.com&quot;</span>&#125;<br>	r = <span class="hljs-built_in">real</span>.Retriever&#123;&#125;<br>	fmt.Println(download(r))<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="1-4-接口的值类型">1.4 接口的值类型</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211101235059102.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211101235059102">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211101235115166.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211101235115166">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;learngo/retriever/mock&quot;</span><br>	<span class="hljs-string">&quot;learngo/retriever/real&quot;</span><br>	<span class="hljs-string">&quot;time&quot;</span><br>)<br><br><span class="hljs-keyword">type</span> Retriever <span class="hljs-keyword">interface</span> &#123;<br>	Get(url <span class="hljs-keyword">string</span>) <span class="hljs-keyword">string</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">download</span><span class="hljs-params">(r Retriever)</span> <span class="hljs-title">string</span></span> &#123;<br>	<span class="hljs-keyword">return</span> r.Get(<span class="hljs-string">&quot;http://www.imooc.com&quot;</span>)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">inspect</span><span class="hljs-params">(r Retriever)</span></span> &#123;<br>    <span class="hljs-comment">// Type switch</span><br>	<span class="hljs-keyword">switch</span> v := r.(<span class="hljs-keyword">type</span>) &#123;<br>	<span class="hljs-keyword">case</span> mock.Retriever:<br>		fmt.Println(<span class="hljs-string">&quot;Contents:&quot;</span>, v.Contents)<br>	<span class="hljs-keyword">case</span> *<span class="hljs-built_in">real</span>.Retriever:<br>		fmt.Println(<span class="hljs-string">&quot;UserAgent:&quot;</span>, v.UserAgent)<br>	&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	<span class="hljs-keyword">var</span> r Retriever<br>	r = mock.Retriever&#123;<span class="hljs-string">&quot;this is fake imooc.com&quot;</span>&#125;<br>	inspect(r)<br>	r = &amp;<span class="hljs-built_in">real</span>.Retriever&#123;<br>		UserAgent: <span class="hljs-string">&quot;Mozilla/5.0&quot;</span>,<br>		TimeOut:   time.Minute,<br>	&#125;<br>	inspect(r)<br><br>	<span class="hljs-comment">// Type assertion</span><br>	<span class="hljs-comment">//realRetriever := r.(*real.Retriever)</span><br>	<span class="hljs-comment">//fmt.Println(realRetriever.TimeOut)</span><br>	<span class="hljs-keyword">if</span> mockRetriever, ok := r.(mock.Retriever); ok &#123;<br>		fmt.Println(mockRetriever.Contents)<br>	&#125; <span class="hljs-keyword">else</span> &#123;<br>		fmt.Println(<span class="hljs-string">&quot;not a mock retriever&quot;</span>)<br>	&#125;<br><br>	<span class="hljs-comment">//fmt.Println(download(r))</span><br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="1-5-接口的组合">1.5 接口的组合</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// mock.go</span><br><span class="hljs-keyword">package</span> mock<br><br><span class="hljs-keyword">type</span> Retriever <span class="hljs-keyword">struct</span> &#123;<br>	Contents <span class="hljs-keyword">string</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r *Retriever)</span> <span class="hljs-title">Post</span><span class="hljs-params">(url <span class="hljs-keyword">string</span>,</span></span><br><span class="hljs-params"><span class="hljs-function">	form <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">string</span>)</span> <span class="hljs-title">string</span></span> &#123;<br>	r.Contents = form[<span class="hljs-string">&quot;contents&quot;</span>]<br>	<span class="hljs-keyword">return</span> <span class="hljs-string">&quot;ok&quot;</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r *Retriever)</span> <span class="hljs-title">Get</span><span class="hljs-params">(url <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">string</span></span> &#123;<br>	<span class="hljs-keyword">return</span> r.Contents<br>&#125;<br></code></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// main.go</span><br><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;learngo/retriever/mock&quot;</span><br>	<span class="hljs-string">&quot;learngo/retriever/real&quot;</span><br>	<span class="hljs-string">&quot;time&quot;</span><br>)<br><br><span class="hljs-keyword">type</span> Retriever <span class="hljs-keyword">interface</span> &#123;<br>	Get(url <span class="hljs-keyword">string</span>) <span class="hljs-keyword">string</span><br>&#125;<br><br><span class="hljs-keyword">type</span> Poster <span class="hljs-keyword">interface</span> &#123;<br>	Post(url <span class="hljs-keyword">string</span>,<br>		form <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">string</span>) <span class="hljs-keyword">string</span><br>&#125;<br><br><span class="hljs-keyword">const</span> url = <span class="hljs-string">&quot;http://www.imooc.com&quot;</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">download</span><span class="hljs-params">(r Retriever)</span> <span class="hljs-title">string</span></span> &#123;<br>	<span class="hljs-keyword">return</span> r.Get(url)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">post</span><span class="hljs-params">(poster Poster)</span></span> &#123;<br>	poster.Post(url,<br>		<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">string</span>&#123;<br>			<span class="hljs-string">&quot;name&quot;</span>:   <span class="hljs-string">&quot;ccmouse&quot;</span>,<br>			<span class="hljs-string">&quot;course&quot;</span>: <span class="hljs-string">&quot;golang&quot;</span>,<br>		&#125;)<br>&#125;<br><br><span class="hljs-keyword">type</span> RetrieverPoster <span class="hljs-keyword">interface</span> &#123;<br>	Retriever<br>	Poster<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">session</span><span class="hljs-params">(s RetrieverPoster)</span> <span class="hljs-title">string</span></span> &#123;<br>	s.Post(url, <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">string</span>&#123;<br>		<span class="hljs-string">&quot;contents&quot;</span>: <span class="hljs-string">&quot;another faked imooc.com&quot;</span>,<br>	&#125;)<br>	<span class="hljs-keyword">return</span> s.Get(url)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">inspect</span><span class="hljs-params">(r Retriever)</span></span> &#123;<br>	<span class="hljs-keyword">switch</span> v := r.(<span class="hljs-keyword">type</span>) &#123;<br>	<span class="hljs-keyword">case</span> *mock.Retriever:<br>		fmt.Println(<span class="hljs-string">&quot;Contents:&quot;</span>, v.Contents)<br>	<span class="hljs-keyword">case</span> *<span class="hljs-built_in">real</span>.Retriever:<br>		fmt.Println(<span class="hljs-string">&quot;UserAgent:&quot;</span>, v.UserAgent)<br>	&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	<span class="hljs-keyword">var</span> r Retriever<br>	retriever := mock.Retriever&#123;<br>		<span class="hljs-string">&quot;this is fake imooc.com&quot;</span>&#125;<br>	r = &amp;retriever<br>	inspect(r)<br>	r = &amp;<span class="hljs-built_in">real</span>.Retriever&#123;<br>		UserAgent: <span class="hljs-string">&quot;Mozilla/5.0&quot;</span>,<br>		TimeOut:   time.Minute,<br>	&#125;<br>	inspect(r)<br><br>	<span class="hljs-comment">// Type assertion</span><br>	<span class="hljs-comment">//realRetriever := r.(*real.Retriever)</span><br>	<span class="hljs-comment">//fmt.Println(realRetriever.TimeOut)</span><br>	<span class="hljs-keyword">if</span> mockRetriever, ok := r.(*mock.Retriever); ok &#123;<br>		fmt.Println(mockRetriever.Contents)<br>	&#125; <span class="hljs-keyword">else</span> &#123;<br>		fmt.Println(<span class="hljs-string">&quot;not a mock retriever&quot;</span>)<br>	&#125;<br>	fmt.Println(<span class="hljs-string">&quot;Try a session&quot;</span>)<br>	fmt.Println(session(&amp;retriever))<br>	<span class="hljs-comment">//fmt.Println(download(r))</span><br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="1-6-常用系统接口">1.6 常用系统接口</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211102002145016.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211102002145016">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211102002201041.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211102002201041">
<h3 id="1-6-1-string">1.6.1 string()</h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// mock.go</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r *Retriever)</span> <span class="hljs-title">String</span><span class="hljs-params">()</span> <span class="hljs-title">string</span></span> &#123;<br>	<span class="hljs-keyword">return</span> fmt.Sprintf(<br>		<span class="hljs-string">&quot;Retriever: &#123;Contents=%s&#125;&quot;</span>, r.Contents)<br>&#125;<br></code></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// main.go</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">inspect</span><span class="hljs-params">(r Retriever)</span></span> &#123;<br>    fmt.Println(<span class="hljs-string">&quot;Inspecting&quot;</span>, r) <span class="hljs-comment">// 打印的时候会调用接口中的string()</span><br>	fmt.Printf(<span class="hljs-string">&quot; &gt; %T %v\n&quot;</span>, r, r)<br>	fmt.Println(<span class="hljs-string">&quot; &gt; Type switch:&quot;</span>)<br>	<span class="hljs-keyword">switch</span> v := r.(<span class="hljs-keyword">type</span>) &#123;<br>	<span class="hljs-keyword">case</span> *mock.Retriever:<br>		fmt.Println(<span class="hljs-string">&quot;Contents:&quot;</span>, v.Contents)<br>	<span class="hljs-keyword">case</span> *<span class="hljs-built_in">real</span>.Retriever:<br>		fmt.Println(<span class="hljs-string">&quot;UserAgent:&quot;</span>, v.UserAgent)<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="1-6-2-writer">1.6.2 writer()</h3>
<h3 id="1-6-3-reader">1.6.3 reader()</h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// loop.go</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">printFileContents</span><span class="hljs-params">(reader io.Reader)</span></span> &#123;<br>	scanner := bufio.NewScanner(reader)<br><br>	<span class="hljs-keyword">for</span> scanner.Scan() &#123;<br>		fmt.Println(scanner.Text())<br>	&#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>
<h1>2.函数与闭包</h1>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111153510991.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111153510991">
<h2 id="2-1-函数式编程">2.1 函数式编程</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111153549176.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111153549176">
<h2 id="2-2-闭包">2.2 闭包</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111154520020.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111154520020">
<p>sum: 自由变量</p>
<p>v: 局部变量</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">adder</span><span class="hljs-params">()</span> <span class="hljs-title">func</span><span class="hljs-params">(<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> &#123;<br>	sum := <span class="hljs-number">0</span><br>	<span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(v <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> &#123;<br>		sum += v<br>		<span class="hljs-keyword">return</span> sum<br>	&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	a := adder()<br>	<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ &#123;<br>		fmt.Printf(<span class="hljs-string">&quot;0 + 1 + ... + %d = %d\n&quot;</span>,<br>			i, a(i))<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111154903585.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111154903585">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111154935513.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111154935513">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111155046274.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111155046274">
<h2 id="2-3-Go中闭包的应用">2.3 Go中闭包的应用</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111161606528.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111161606528">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111162320312.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111162320312">
<h1>3. 资源管理与出错处理</h1>
<h2 id="3-1-defer调用">3.1 defer调用</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">writeFile</span><span class="hljs-params">(filename <span class="hljs-keyword">string</span>)</span></span> &#123;<br>	file, err := os.Create(filename)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(err)<br>	&#125;<br>	<span class="hljs-keyword">defer</span> file.Close()<br><br>	writer := bufio.NewWriter(file)<br>	<span class="hljs-keyword">defer</span> writer.Flush()<br><br>	f := fib.Fibonacci()<br>	<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">20</span>; i++ &#123;<br>		fmt.Fprintln(writer, f())<br>	&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	writeFile(<span class="hljs-string">&quot;fib.txt&quot;</span>)<br>&#125;<br></code></pre></td></tr></table></figure>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111163323528.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111163323528">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111163356349.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111163356349">
<h2 id="3-2-错误处理">3.2 错误处理</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111164546831.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111164546831">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111170812777.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111170812777">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">type</span> appHandler <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(writer http.ResponseWriter,</span></span><br><span class="hljs-params"><span class="hljs-function">	request *http.Request)</span> <span class="hljs-title">error</span></span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">errWrapper</span><span class="hljs-params">(</span></span><br><span class="hljs-params"><span class="hljs-function">	handler appHandler)</span> <span class="hljs-title">func</span><span class="hljs-params">(</span></span><br><span class="hljs-params"><span class="hljs-function">	http.ResponseWriter, *http.Request)</span></span> &#123;<br>	<span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(writer http.ResponseWriter,</span></span><br><span class="hljs-params"><span class="hljs-function">		request *http.Request)</span></span> &#123;<br>		err := handler(writer, request)<br>		<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>			code := http.StatusOK<br>			<span class="hljs-keyword">switch</span> &#123;<br>			<span class="hljs-keyword">case</span> os.IsNotExist(err):<br>				code = http.StatusNotFound<br>			<span class="hljs-keyword">case</span> os.IsPermission(err):<br>				code = http.StatusForbidden<br>			<span class="hljs-keyword">default</span>:<br>				code = http.StatusInternalServerError<br>			&#125;<br>			http.Error(<br>				writer,<br>				http.StatusText(code),<br>				code)<br>		&#125;<br>	&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	http.HandleFunc(<span class="hljs-string">&quot;/list/&quot;</span>,<br>		errWrapper(filelisting.HandleFileList))<br>	err := http.ListenAndServe(<span class="hljs-string">&quot;:8888&quot;</span>, <span class="hljs-literal">nil</span>)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(err)<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// web.go</span><br><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;learngo/errhandling/filelistingserver/filelisting&quot;</span><br>	<span class="hljs-string">&quot;log&quot;</span><br>	<span class="hljs-string">&quot;net/http&quot;</span><br>	<span class="hljs-string">&quot;os&quot;</span><br>)<br><br><span class="hljs-keyword">type</span> appHandler <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(writer http.ResponseWriter,</span></span><br><span class="hljs-params"><span class="hljs-function">	request *http.Request)</span> <span class="hljs-title">error</span></span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">errWrapper</span><span class="hljs-params">(</span></span><br><span class="hljs-params"><span class="hljs-function">	handler appHandler)</span> <span class="hljs-title">func</span><span class="hljs-params">(</span></span><br><span class="hljs-params"><span class="hljs-function">	http.ResponseWriter, *http.Request)</span></span> &#123;<br>	<span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(writer http.ResponseWriter,</span></span><br><span class="hljs-params"><span class="hljs-function">		request *http.Request)</span></span> &#123;<br>		<span class="hljs-keyword">defer</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>			<span class="hljs-keyword">if</span> r := <span class="hljs-built_in">recover</span>(); r != <span class="hljs-literal">nil</span> &#123;<br>				log.Printf(<span class="hljs-string">&quot;Panic: %v&quot;</span>, r)<br>				http.Error(writer,<br>					http.StatusText(http.StatusInternalServerError),<br>					http.StatusInternalServerError)<br>			&#125;<br>		&#125;()<br>		err := handler(writer, request)<br>		<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>			log.Printf(<span class="hljs-string">&quot;Error occurred &quot;</span>+<br>				<span class="hljs-string">&quot;handling request: %s&quot;</span>,<br>				err.Error())<br><br>			<span class="hljs-keyword">if</span> userErr, ok := err.(userError); ok &#123;<br>				http.Error(writer,<br>					userErr.Message(),<br>					http.StatusBadRequest)<br>				<span class="hljs-keyword">return</span><br>			&#125;<br><br>			code := http.StatusOK<br>			<span class="hljs-keyword">switch</span> &#123;<br>			<span class="hljs-keyword">case</span> os.IsNotExist(err):<br>				code = http.StatusNotFound<br>			<span class="hljs-keyword">case</span> os.IsPermission(err):<br>				code = http.StatusForbidden<br>			<span class="hljs-keyword">default</span>:<br>				code = http.StatusInternalServerError<br>			&#125;<br>			http.Error(<br>				writer,<br>				http.StatusText(code),<br>				code)<br>		&#125;<br>	&#125;<br>&#125;<br><br><span class="hljs-keyword">type</span> userError <span class="hljs-keyword">interface</span> &#123;<br>	error<br>	Message() <span class="hljs-keyword">string</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	http.HandleFunc(<span class="hljs-string">&quot;/&quot;</span>,<br>		errWrapper(filelisting.HandleFileList))<br>	err := http.ListenAndServe(<span class="hljs-string">&quot;:8888&quot;</span>, <span class="hljs-literal">nil</span>)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(err)<br>	&#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// handler.go</span><br><span class="hljs-keyword">package</span> filelisting<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;io/ioutil&quot;</span><br>	<span class="hljs-string">&quot;net/http&quot;</span><br>	<span class="hljs-string">&quot;os&quot;</span><br>	<span class="hljs-string">&quot;strings&quot;</span><br>)<br><br><span class="hljs-keyword">const</span> prefix = <span class="hljs-string">&quot;/list/&quot;</span><br><br><span class="hljs-keyword">type</span> userError <span class="hljs-keyword">string</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(e userError)</span> <span class="hljs-title">Error</span><span class="hljs-params">()</span> <span class="hljs-title">string</span></span> &#123;<br>	<span class="hljs-keyword">return</span> e.Message()<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(e userError)</span> <span class="hljs-title">Message</span><span class="hljs-params">()</span> <span class="hljs-title">string</span></span> &#123;<br>	<span class="hljs-keyword">return</span> <span class="hljs-keyword">string</span>(e)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">HandleFileList</span><span class="hljs-params">(writer http.ResponseWriter,</span></span><br><span class="hljs-params"><span class="hljs-function">	request *http.Request)</span> <span class="hljs-title">error</span></span> &#123;<br>	<span class="hljs-keyword">if</span> strings.Index(<br>		request.URL.Path, prefix) != <span class="hljs-number">0</span> &#123;<br>		<span class="hljs-keyword">return</span> userError(<span class="hljs-string">&quot;path must start &quot;</span> +<br>			<span class="hljs-string">&quot;with &quot;</span> + prefix)<br>	&#125;<br>	path := request.URL.Path[<span class="hljs-built_in">len</span>(<span class="hljs-string">&quot;/list/&quot;</span>):]<br>	file, err := os.Open(path)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-keyword">return</span> err<br>	&#125;<br>	<span class="hljs-keyword">defer</span> file.Close()<br><br>	all, err := ioutil.ReadAll(file)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-keyword">return</span> err<br>	&#125;<br><br>	writer.Write(all)<br>	<span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span><br>&#125;<br></code></pre></td></tr></table></figure>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111173330134.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111173330134">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111173437787.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111173437787">
<h1>4. 测试</h1>
<h2 id="4-1-传统测试">4.1 传统测试</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211111175214834.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211111175214834">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112150609211.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112150609211">
<h2 id="4-2-表格驱动测试">4.2 表格驱动测试</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112150633341.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112150633341">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112150754864.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112150754864">
<h2 id="4-3-测试">4.3 测试</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> <span class="hljs-string">&quot;testing&quot;</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestSubstr</span><span class="hljs-params">(t *testing.T)</span></span> &#123;<br>	tests := []<span class="hljs-keyword">struct</span> &#123;<br>		s   <span class="hljs-keyword">string</span><br>		ans <span class="hljs-keyword">int</span><br>	&#125;&#123;<br>		<span class="hljs-comment">// Normal cases</span><br>		&#123;<span class="hljs-string">&quot;abcabcabc&quot;</span>, <span class="hljs-number">3</span>&#125;,<br>		&#123;<span class="hljs-string">&quot;aaaaaaaaaa&quot;</span>, <span class="hljs-number">1</span>&#125;,<br><br>		<span class="hljs-comment">// Edge cases</span><br>		&#123;<span class="hljs-string">&quot;&quot;</span>, <span class="hljs-number">0</span>&#125;,<br>		&#123;<span class="hljs-string">&quot;b&quot;</span>, <span class="hljs-number">1</span>&#125;,<br>		&#123;<span class="hljs-string">&quot;bbbbb&quot;</span>, <span class="hljs-number">1</span>&#125;,<br><br>		<span class="hljs-comment">// Chinese supporrt</span><br>		&#123;<span class="hljs-string">&quot;木木木木啊啊啊啊啊啊啊啊&quot;</span>, <span class="hljs-number">2</span>&#125;,<br>		&#123;<span class="hljs-string">&quot;这里是慕课网&quot;</span>, <span class="hljs-number">6</span>&#125;,<br>	&#125;<br><br>	<span class="hljs-keyword">for</span> _, tt := <span class="hljs-keyword">range</span> tests &#123;<br>		actual := lengthOfNonRepeatingSubStr(tt.s)<br>		<span class="hljs-keyword">if</span> actual != tt.ans &#123;<br>			t.Errorf(<span class="hljs-string">&quot;got %d for input %s;&quot;</span>+<br>				<span class="hljs-string">&quot;expected %d&quot;</span>,<br>				actual, tt.s, tt.ans)<br>		&#125;<br>	&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">BenchmarkSubstr</span><span class="hljs-params">(b *testing.B)</span></span> &#123;<br>	s := <span class="hljs-string">&quot;黑化肥会会花灰化肥会挥发会废话&quot;</span><br>	<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">13</span>; i++ &#123;<br>		s = s + s<br>	&#125;<br>	ans := <span class="hljs-number">8</span><br><br>	b.Logf(<span class="hljs-string">&quot;len(s) = %d&quot;</span>, <span class="hljs-built_in">len</span>(s))<br>	b.ResetTimer()<br><br>	<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; b.N; i++ &#123;<br>		actual := lengthOfNonRepeatingSubStr(s)<br>		<span class="hljs-keyword">if</span> actual != ans &#123;<br>			b.Errorf(<span class="hljs-string">&quot;got %d for input %s;&quot;</span>+<br>				<span class="hljs-string">&quot;expected %d&quot;</span>,<br>				actual, s, ans)<br>		&#125;<br>	&#125;<br>&#125;<br><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> <span class="hljs-string">&quot;testing&quot;</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestTriangle</span><span class="hljs-params">(t *testing.T)</span></span> &#123;<br>	tests := []<span class="hljs-keyword">struct</span>&#123; a, b, c <span class="hljs-keyword">int</span> &#125;&#123;<br>		&#123;<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>&#125;,<br>		&#123;<span class="hljs-number">5</span>, <span class="hljs-number">12</span>, <span class="hljs-number">13</span>&#125;,<br>		&#123;<span class="hljs-number">8</span>, <span class="hljs-number">15</span>, <span class="hljs-number">17</span>&#125;,<br>		&#123;<span class="hljs-number">12</span>, <span class="hljs-number">35</span>, <span class="hljs-number">37</span>&#125;,<br>		&#123;<span class="hljs-number">30000</span>, <span class="hljs-number">40000</span>, <span class="hljs-number">50000</span>&#125;,<br>	&#125;<br><br>	<span class="hljs-keyword">for</span> _, tt := <span class="hljs-keyword">range</span> tests &#123;<br>		<span class="hljs-keyword">if</span> actual := calcTriangle(tt.a, tt.b); actual != tt.c &#123;<br>			t.Errorf(<span class="hljs-string">&quot;calcTriangle(%d, %d);&quot;</span>+<br>				<span class="hljs-string">&quot;got %d; expected %d&quot;</span>,<br>				tt.a, tt.b, actual, tt.c)<br>		&#125;<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>还可以用在当前目录命令行执行：</p>
<figure class="highlight cmd"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cmd">go test + 各种命令可以进行各种测试<br></code></pre></td></tr></table></figure>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112155503740.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112155503740">
<h2 id="4-4-http-测试">4.4 http 测试</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112164600539.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112164600539">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;errors&quot;</span><br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;io/ioutil&quot;</span><br>	<span class="hljs-string">&quot;net/http&quot;</span><br>	<span class="hljs-string">&quot;net/http/httptest&quot;</span><br>	<span class="hljs-string">&quot;os&quot;</span><br>	<span class="hljs-string">&quot;strings&quot;</span><br>	<span class="hljs-string">&quot;testing&quot;</span><br>)<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">errPanic</span><span class="hljs-params">(writer http.ResponseWriter,</span></span><br><span class="hljs-params"><span class="hljs-function">	request *http.Request)</span> <span class="hljs-title">error</span></span> &#123;<br>	<span class="hljs-built_in">panic</span>(<span class="hljs-number">123</span>)<br>&#125;<br><br><span class="hljs-keyword">type</span> testinguserError <span class="hljs-keyword">string</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(e testinguserError)</span> <span class="hljs-title">Error</span><span class="hljs-params">()</span> <span class="hljs-title">string</span></span> &#123;<br>	<span class="hljs-keyword">return</span> e.Message()<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(e testinguserError)</span> <span class="hljs-title">Message</span><span class="hljs-params">()</span> <span class="hljs-title">string</span></span> &#123;<br>	<span class="hljs-keyword">return</span> <span class="hljs-keyword">string</span>(e)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">errUserError</span><span class="hljs-params">(writer http.ResponseWriter,</span></span><br><span class="hljs-params"><span class="hljs-function">	request *http.Request)</span> <span class="hljs-title">error</span></span> &#123;<br>	<span class="hljs-keyword">return</span> testinguserError(<span class="hljs-string">&quot;user error&quot;</span>)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">errNotFound</span><span class="hljs-params">(writer http.ResponseWriter,</span></span><br><span class="hljs-params"><span class="hljs-function">	request *http.Request)</span> <span class="hljs-title">error</span></span> &#123;<br>	<span class="hljs-keyword">return</span> os.ErrNotExist<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">errNoPermission</span><span class="hljs-params">(writer http.ResponseWriter,</span></span><br><span class="hljs-params"><span class="hljs-function">	request *http.Request)</span> <span class="hljs-title">error</span></span> &#123;<br>	<span class="hljs-keyword">return</span> os.ErrPermission<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">errUnknown</span><span class="hljs-params">(writer http.ResponseWriter,</span></span><br><span class="hljs-params"><span class="hljs-function">	request *http.Request)</span> <span class="hljs-title">error</span></span> &#123;<br>	<span class="hljs-keyword">return</span> errors.New(<span class="hljs-string">&quot;unknown error&quot;</span>)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">noError</span><span class="hljs-params">(writer http.ResponseWriter,</span></span><br><span class="hljs-params"><span class="hljs-function">	request *http.Request)</span> <span class="hljs-title">error</span></span> &#123;<br>	fmt.Fprintln(writer, <span class="hljs-string">&quot;no error&quot;</span>)<br>	<span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span><br>&#125;<br><br><span class="hljs-keyword">var</span> tests = []<span class="hljs-keyword">struct</span> &#123;<br>	h       appHandler<br>	code    <span class="hljs-keyword">int</span><br>	message <span class="hljs-keyword">string</span><br>&#125;&#123;<br>	&#123;errPanic, <span class="hljs-number">500</span>, <span class="hljs-string">&quot;Internal Server Error&quot;</span>&#125;,<br>	&#123;errUserError, <span class="hljs-number">400</span>, <span class="hljs-string">&quot;user error&quot;</span>&#125;,<br>	&#123;errNotFound, <span class="hljs-number">404</span>, <span class="hljs-string">&quot;Not Found&quot;</span>&#125;,<br>	&#123;errNoPermission, <span class="hljs-number">403</span>, <span class="hljs-string">&quot;Forbidden&quot;</span>&#125;,<br>	&#123;errUnknown, <span class="hljs-number">500</span>, <span class="hljs-string">&quot;Internal Server Error&quot;</span>&#125;,<br>	&#123;noError, <span class="hljs-number">200</span>, <span class="hljs-string">&quot;no error&quot;</span>&#125;,<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestErrWrapper</span><span class="hljs-params">(t *testing.T)</span></span> &#123;<br>	<span class="hljs-keyword">for</span> _, tt := <span class="hljs-keyword">range</span> tests &#123;<br>		f := errWrapper(tt.h)<br>		<span class="hljs-comment">// 使用假的Request/Response</span><br>		response := httptest.NewRecorder()<br>		request := httptest.NewRequest(<br>			http.MethodGet,<br>			<span class="hljs-string">&quot;http://www.imooc.com&quot;</span>, <span class="hljs-literal">nil</span>)<br>		f(response, request)<br><br>		verifyResponse(response.Result(),<br>			tt.code, tt.message, t)<br>	&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestErrWrapperInServer</span><span class="hljs-params">(t *testing.T)</span></span> &#123;<br>	<span class="hljs-keyword">for</span> _, tt := <span class="hljs-keyword">range</span> tests &#123;<br>		f := errWrapper(tt.h)<br>		<span class="hljs-comment">// 启动服务器</span><br>		server := httptest.NewServer(<br>			http.HandlerFunc(f))<br>		resp, _ := http.Get(server.URL)<br><br>		verifyResponse(resp,<br>			tt.code, tt.message, t)<br>	&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">verifyResponse</span><span class="hljs-params">(resp *http.Response,</span></span><br><span class="hljs-params"><span class="hljs-function">	expextedCode <span class="hljs-keyword">int</span>, expectedMsg <span class="hljs-keyword">string</span>,</span></span><br><span class="hljs-params"><span class="hljs-function">	t *testing.T)</span></span> &#123;<br>	b, _ := ioutil.ReadAll(resp.Body)<br>	body := strings.Trim(<span class="hljs-keyword">string</span>(b), <span class="hljs-string">&quot;\n&quot;</span>)<br>	<span class="hljs-keyword">if</span> resp.StatusCode != expextedCode ||<br>		body != expectedMsg &#123;<br>		t.Errorf(<span class="hljs-string">&quot;expect (%d, %s); &quot;</span>+<br>			<span class="hljs-string">&quot;got (%d, %s)&quot;</span>,<br>			expextedCode, expectedMsg,<br>			resp.StatusCode, body)<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="4-5-生成文档和示例代码">4.5 生成文档和示例代码</h2>
<p>生成文档：go doc 或者 godoc</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> queue<br><br><span class="hljs-comment">// An FIFO queue.</span><br><span class="hljs-keyword">type</span> Queue []<span class="hljs-keyword">int</span><br><br><span class="hljs-comment">// Pushes the element into the queue.</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(q *Queue)</span> <span class="hljs-title">Push</span><span class="hljs-params">(v <span class="hljs-keyword">int</span>)</span></span> &#123;<br>	*q = <span class="hljs-built_in">append</span>(*q, v)<br>&#125;<br><br><span class="hljs-comment">// Pops emement from head.</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(q *Queue)</span> <span class="hljs-title">Pop</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> &#123;<br>	head := (*q)[<span class="hljs-number">0</span>]<br>	*q = (*q)[<span class="hljs-number">1</span>:]<br>	<span class="hljs-keyword">return</span> head<br>&#125;<br><br><span class="hljs-comment">// Returns if the queue is empty or not.</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(q *Queue)</span> <span class="hljs-title">IsEmpty</span><span class="hljs-params">()</span> <span class="hljs-title">bool</span></span> &#123;<br>	<span class="hljs-keyword">return</span> <span class="hljs-built_in">len</span>(*q) == <span class="hljs-number">0</span><br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="通过godoc-生成文档html-可以查看相关内容及注释">通过godoc 生成文档html 可以查看相关内容及注释</h3>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112170120534.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112170120534">
<h3 id="通过文档查看所写的示例代码">通过文档查看所写的示例代码</h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> queue<br><br><span class="hljs-keyword">import</span> <span class="hljs-string">&quot;fmt&quot;</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">ExampleQueue_Pop</span><span class="hljs-params">()</span></span> &#123;<br>	q := Queue&#123;<span class="hljs-number">1</span>&#125;<br>	q.Push(<span class="hljs-number">2</span>)<br>	q.Push(<span class="hljs-number">3</span>)<br>	fmt.Println(q.Pop())<br>	fmt.Println(q.Pop())<br>	fmt.Println(q.IsEmpty())<br><br>	fmt.Println(q.Pop())<br>	fmt.Println(q.IsEmpty())<br><br>	<span class="hljs-comment">// Output:</span><br>	<span class="hljs-comment">// 1</span><br>	<span class="hljs-comment">// 2</span><br>	<span class="hljs-comment">// false</span><br>	<span class="hljs-comment">// 3</span><br>	<span class="hljs-comment">// true</span><br>&#125;<br></code></pre></td></tr></table></figure>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112170202638.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112170202638">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112170232214.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112170232214">
<h1>5. goroutine</h1>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112170405190.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112170405190">
<h2 id="5-1-协程-swig￼70">5.1 协程<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112174613953.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112174613953"></h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112175349580.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112175349580">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112175443743.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112175443743">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112175548923.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112175548923">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112175553512.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112175553512">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112175635562.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112175635562">
<h2 id="5-2-goroutine定义">5.2 goroutine定义</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112175736156.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112175736156">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112175808291.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112175808291">
<h1>6. channel</h1>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112180001671.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112180001671">
<h2 id="6-1-channel语法">6.1 channel语法</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;time&quot;</span><br>)<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">worker</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>, c <span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)</span></span> &#123;<br>	<span class="hljs-keyword">for</span> n := <span class="hljs-keyword">range</span> c &#123;<br>		fmt.Printf(<span class="hljs-string">&quot;Worker %d received %d\n&quot;</span>,<br>			id, n)<br>	&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">creteWorker</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">chan</span>&lt;- <span class="hljs-title">int</span></span> &#123;<br>	c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)<br>	<span class="hljs-keyword">go</span> worker(id, c)<br>	<span class="hljs-keyword">return</span> c<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">chanDemo</span><span class="hljs-params">()</span></span> &#123;<br>	<span class="hljs-comment">//var c chan int // c == nil</span><br><br>	<span class="hljs-keyword">var</span> channels [<span class="hljs-number">10</span>]<span class="hljs-keyword">chan</span>&lt;- <span class="hljs-keyword">int</span><br>	<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ &#123;<br>		channels[i] = creteWorker(i)<br>	&#125;<br><br>	<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ &#123;<br>		channels[i] &lt;- <span class="hljs-string">&#x27;a&#x27;</span> + i<br>	&#125;<br>	time.Sleep(time.Millisecond)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">bufferedChannel</span><span class="hljs-params">()</span></span> &#123;<br>	c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>, <span class="hljs-number">3</span>)<br>	<span class="hljs-keyword">go</span> worker(<span class="hljs-number">0</span>, c)<br>	c &lt;- <span class="hljs-string">&#x27;a&#x27;</span><br>	c &lt;- <span class="hljs-string">&#x27;b&#x27;</span><br>	c &lt;- <span class="hljs-string">&#x27;c&#x27;</span><br>	c &lt;- <span class="hljs-string">&#x27;d&#x27;</span><br>	time.Sleep(time.Millisecond)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">channelClose</span><span class="hljs-params">()</span></span> &#123;<br>	c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)<br>	<span class="hljs-keyword">go</span> worker(<span class="hljs-number">0</span>, c)<br>	c &lt;- <span class="hljs-string">&#x27;a&#x27;</span><br>	c &lt;- <span class="hljs-string">&#x27;b&#x27;</span><br>	c &lt;- <span class="hljs-string">&#x27;c&#x27;</span><br>	c &lt;- <span class="hljs-string">&#x27;d&#x27;</span><br>	<span class="hljs-built_in">close</span>(c)<br>	time.Sleep(time.Millisecond)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	fmt.Println(<span class="hljs-string">&quot;Channel as first-class citizen&quot;</span>)<br>	chanDemo()<br>	fmt.Println(<span class="hljs-string">&quot;Buffered channel&quot;</span>)<br>	bufferedChannel()<br>	fmt.Println(<span class="hljs-string">&quot;Channel close and range&quot;</span>)<br>	channelClose()<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="6-2-channel应用">6.2 channel应用</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112204830267.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112204830267">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112204852518.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112204852518">
<h3 id="6-2-1-使用Channel来等待goroutine结束以及WatiGroup的使用">6.2.1 使用Channel来等待goroutine结束以及WatiGroup的使用</h3>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112214505530.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112214505530">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;sync&quot;</span><br>)<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">doWorker</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>,</span></span><br><span class="hljs-params"><span class="hljs-function">	w worker)</span></span> &#123;<br>	<span class="hljs-keyword">for</span> n := <span class="hljs-keyword">range</span> w.in &#123;<br>		fmt.Printf(<span class="hljs-string">&quot;Worker %d received %c\n&quot;</span>,<br>			id, n)<br>		w.done()<br>	&#125;<br>&#125;<br><br><span class="hljs-keyword">type</span> worker <span class="hljs-keyword">struct</span> &#123;<br>	in   <span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span><br>	done <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">creteWorker</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>,</span></span><br><span class="hljs-params"><span class="hljs-function">	wg *sync.WaitGroup)</span> <span class="hljs-title">worker</span></span> &#123;<br>	w := worker&#123;<br>		in: <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>),<br>		done: <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>			wg.Done()<br>		&#125;,<br>	&#125;<br>	<span class="hljs-keyword">go</span> doWorker(id, w)<br>	<span class="hljs-keyword">return</span> w<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">chanDemo</span><span class="hljs-params">()</span></span> &#123;<br>	<span class="hljs-keyword">var</span> wg sync.WaitGroup<br><br>	<span class="hljs-keyword">var</span> workers [<span class="hljs-number">10</span>]worker<br>	<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ &#123;<br>		workers[i] = creteWorker(i, &amp;wg)<br>	&#125;<br><br>	wg.Add(<span class="hljs-number">20</span>)<br>	<span class="hljs-keyword">for</span> i, worker := <span class="hljs-keyword">range</span> workers &#123;<br>		worker.in &lt;- <span class="hljs-string">&#x27;a&#x27;</span> + i<br>	&#125;<br>	<span class="hljs-keyword">for</span> i, worker := <span class="hljs-keyword">range</span> workers &#123;<br>		worker.in &lt;- <span class="hljs-string">&#x27;A&#x27;</span> + i<br>	&#125;<br><br>	wg.Wait()<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	chanDemo()<br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="6-2-1-使用Channel来实现树的遍历">6.2.1 使用Channel来实现树的遍历</h3>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112215041941.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112215041941">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// traveral.go</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(node *Node)</span> <span class="hljs-title">TraverseWithChannel</span><span class="hljs-params">()</span> <span class="hljs-title">chan</span> *<span class="hljs-title">Node</span></span> &#123;<br>	out := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> *Node)<br>	<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>		node.TraverseFunc(<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(node *Node)</span></span> &#123;<br>			out &lt;- node<br>		&#125;)<br>		<span class="hljs-built_in">close</span>(out)<br>	&#125;()<br>	<span class="hljs-keyword">return</span> out<br>&#125;<br><br><span class="hljs-comment">// entry.go</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>    ...<br>    	c := root.TraverseWithChannel()<br>	maxNode := <span class="hljs-number">0</span><br>	<span class="hljs-keyword">for</span> node := <span class="hljs-keyword">range</span> c &#123;<br>		<span class="hljs-keyword">if</span> node.Value &gt; maxNode &#123;<br>			maxNode = node.Value<br>		&#125;<br>	&#125;<br>	fmt.Println(<span class="hljs-string">&quot;Max node value:&quot;</span>, maxNode)<br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="6-2-3-使用Select进行调度">6.2.3 使用Select进行调度</h3>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112222024589.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112222024589">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;math/rand&quot;</span><br>	<span class="hljs-string">&quot;time&quot;</span><br>)<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">generate</span><span class="hljs-params">()</span> <span class="hljs-title">chan</span> <span class="hljs-title">int</span></span> &#123;<br>	out := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)<br>	<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>		i := <span class="hljs-number">0</span><br>		<span class="hljs-keyword">for</span> &#123;<br>			time.Sleep(<br>				time.Duration(rand.Intn(<span class="hljs-number">1500</span>)) *<br>					time.Millisecond)<br>			out &lt;- i<br>			i++<br>		&#125;<br>	&#125;()<br>	<span class="hljs-keyword">return</span> out<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">worker</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>, c <span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)</span></span> &#123;<br>	<span class="hljs-keyword">for</span> n := <span class="hljs-keyword">range</span> c &#123;<br>		time.Sleep(time.Second)<br>		fmt.Printf(<span class="hljs-string">&quot;Worker %d recevied %d\n&quot;</span>,<br>			id, n)<br>	&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">createWorker</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">chan</span>&lt;- <span class="hljs-title">int</span></span> &#123;<br>	c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)<br>	<span class="hljs-keyword">go</span> worker(id, c)<br>	<span class="hljs-keyword">return</span> c<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	<span class="hljs-keyword">var</span> c1, c2 = generate(), generate()<br>	<span class="hljs-keyword">var</span> worker = createWorker(<span class="hljs-number">0</span>)<br><br>	<span class="hljs-keyword">var</span> values []<span class="hljs-keyword">int</span><br>	tm := time.After(<span class="hljs-number">10</span> * time.Second)<br>	tick := time.Tick(time.Second)<br>	<span class="hljs-keyword">for</span> &#123;<br>		<span class="hljs-keyword">var</span> activeWorker <span class="hljs-keyword">chan</span>&lt;- <span class="hljs-keyword">int</span><br>		<span class="hljs-keyword">var</span> activeValue <span class="hljs-keyword">int</span><br>		<span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(values) &gt; <span class="hljs-number">0</span> &#123;<br>			activeWorker = worker<br>			activeValue = values[<span class="hljs-number">0</span>]<br>		&#125;<br><br>		<span class="hljs-keyword">select</span> &#123;<br>		<span class="hljs-keyword">case</span> n := &lt;-c1:<br>			values = <span class="hljs-built_in">append</span>(values, n)<br>		<span class="hljs-keyword">case</span> n := &lt;-c2:<br>			values = <span class="hljs-built_in">append</span>(values, n)<br>		<span class="hljs-keyword">case</span> activeWorker &lt;- activeValue:<br>			values = values[<span class="hljs-number">1</span>:]<br><br>		<span class="hljs-keyword">case</span> &lt;-time.After(<span class="hljs-number">800</span> * time.Millisecond):<br>			fmt.Println(<span class="hljs-string">&quot;timeout&quot;</span>)<br>		<span class="hljs-keyword">case</span> &lt;-tick:<br>			fmt.Println(<span class="hljs-string">&quot;queue len =&quot;</span>, <span class="hljs-built_in">len</span>(values))<br>		<span class="hljs-keyword">case</span> &lt;-tm:<br>			fmt.Println(<span class="hljs-string">&quot;bye&quot;</span>)<br>			<span class="hljs-keyword">return</span><br>		&#125;<br>	&#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="6-3-传统同步机制">6.3 传统同步机制</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112225840284.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112225840284">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;sync&quot;</span><br>	<span class="hljs-string">&quot;time&quot;</span><br>)<br><br><span class="hljs-keyword">type</span> atomicInt <span class="hljs-keyword">struct</span> &#123;<br>	value <span class="hljs-keyword">int</span><br>	lock  sync.Mutex<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(a *atomicInt)</span> <span class="hljs-title">increment</span><span class="hljs-params">()</span></span> &#123;<br>	fmt.Println(<span class="hljs-string">&quot;safe increment&quot;</span>)<br>	<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>		a.lock.Lock()<br>		<span class="hljs-keyword">defer</span> a.lock.Unlock()<br><br>		a.value++<br>	&#125;()<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(a *atomicInt)</span> <span class="hljs-title">get</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> &#123;<br>	a.lock.Lock()<br>	<span class="hljs-keyword">defer</span> a.lock.Unlock()<br>	<span class="hljs-keyword">return</span> a.value<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	<span class="hljs-keyword">var</span> a atomicInt<br>	a.increment()<br>	<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>		a.increment()<br>	&#125;()<br>	time.Sleep(time.Millisecond)<br>	fmt.Println(a.get())<br>&#125;<br></code></pre></td></tr></table></figure>
<h1>7. 并发模式</h1>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112233000986.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112233000986">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;math/rand&quot;</span><br>	<span class="hljs-string">&quot;time&quot;</span><br>)<br><br><span class="hljs-comment">// 生成器</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">msgGen</span><span class="hljs-params">()</span> <span class="hljs-title">chan</span> <span class="hljs-title">string</span></span> &#123;<br>	c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)<br>	<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>		i := <span class="hljs-number">0</span><br>		<span class="hljs-keyword">for</span> &#123;<br>			time.Sleep(time.Duration(rand.Intn(<span class="hljs-number">2000</span>)) * time.Millisecond)<br>			c &lt;- fmt.Sprintf(<span class="hljs-string">&quot;message %d&quot;</span>, i)<br>			i++<br>		&#125;<br>	&#125;()<br>	<span class="hljs-keyword">return</span> c<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	m1 := msgGen()<br>	m2 := msgGen()<br>	<span class="hljs-keyword">for</span> &#123;<br>		fmt.Println(&lt;-m1)<br>		fmt.Println(&lt;-m2)<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// 同时等待多个服务</span><br><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;math/rand&quot;</span><br>	<span class="hljs-string">&quot;time&quot;</span><br>)<br><br><span class="hljs-comment">// 生成器</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">msgGen</span><span class="hljs-params">(name <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">chan</span> <span class="hljs-title">string</span></span> &#123;<br>	c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)<br>	<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>		i := <span class="hljs-number">0</span><br>		<span class="hljs-keyword">for</span> &#123;<br>			time.Sleep(time.Duration(rand.Intn(<span class="hljs-number">2000</span>)) * time.Millisecond)<br>			c &lt;- fmt.Sprintf(<span class="hljs-string">&quot;service %s: message %d&quot;</span>, name, i)<br>			i++<br>		&#125;<br>	&#125;()<br>	<span class="hljs-keyword">return</span> c<br>&#125;<br><br><span class="hljs-comment">// 方法一（适合未知数量或已知）</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fanIn</span><span class="hljs-params">(chs ...<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">chan</span> <span class="hljs-title">string</span></span> &#123;<br>	c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)<br>	<span class="hljs-keyword">for</span> _, ch := <span class="hljs-keyword">range</span> chs &#123;<br>		<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(in <span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span></span> &#123;<br>			<span class="hljs-keyword">for</span> &#123;<br>				c &lt;- &lt;-in<br>			&#125;<br>		&#125;(ch)<br>	&#125;<br>	<span class="hljs-keyword">return</span> c<br>&#125;<br><br><span class="hljs-comment">// 方法二（适合已知数量）</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fanInBySelect</span><span class="hljs-params">(c1, c2 <span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">chan</span> <span class="hljs-title">string</span></span> &#123;<br>	c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)<br>	<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>		<span class="hljs-keyword">for</span> &#123;<br>			<span class="hljs-keyword">select</span> &#123;<br>			<span class="hljs-keyword">case</span> m := &lt;-c1:<br>				c &lt;- m<br>			<span class="hljs-keyword">case</span> m := &lt;-c2:<br>				c &lt;- m<br>			&#125;<br>		&#125;<br>	&#125;()<br>	<span class="hljs-keyword">return</span> c<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	m1 := msgGen(<span class="hljs-string">&quot;service1&quot;</span>)<br>	m2 := msgGen(<span class="hljs-string">&quot;service2&quot;</span>)<br>	m3 := msgGen(<span class="hljs-string">&quot;service3&quot;</span>)<br>	m := fanIn(m1, m2, m3)<br>	<span class="hljs-keyword">for</span> &#123;<br>		fmt.Println(&lt;-m)<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="7-1-任务的控制">7.1 任务的控制</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211112233338553.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211112233338553">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;math/rand&quot;</span><br>	<span class="hljs-string">&quot;time&quot;</span><br>)<br><br><span class="hljs-comment">// 中断  优雅退出</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">msgGen</span><span class="hljs-params">(name <span class="hljs-keyword">string</span>, done <span class="hljs-keyword">chan</span> <span class="hljs-keyword">struct</span>&#123;&#125;)</span> <span class="hljs-title">chan</span> <span class="hljs-title">string</span></span> &#123;<br>	c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)<br>	<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>		i := <span class="hljs-number">0</span><br>		<span class="hljs-keyword">for</span> &#123;<br>			<span class="hljs-keyword">select</span> &#123;<br>			<span class="hljs-keyword">case</span> &lt;-time.After(time.Duration(rand.Intn(<span class="hljs-number">5000</span>)) * time.Millisecond):<br>				c &lt;- fmt.Sprintf(<span class="hljs-string">&quot;service %s: message %d&quot;</span>, name, i)<br>			<span class="hljs-keyword">case</span> &lt;-done:<br>				<span class="hljs-comment">// 优雅退出</span><br>				fmt.Println(<span class="hljs-string">&quot;cleaning up&quot;</span>)<br>				time.Sleep(<span class="hljs-number">2</span> * time.Second)<br>				fmt.Println(<span class="hljs-string">&quot;cleanup done&quot;</span>)<br>				done &lt;- <span class="hljs-keyword">struct</span>&#123;&#125;&#123;&#125;<br>				<span class="hljs-keyword">return</span><br>			&#125;<br>			i++<br>		&#125;<br>	&#125;()<br>	<span class="hljs-keyword">return</span> c<br>&#125;<br><br><span class="hljs-comment">// 方法一（适合未知数量或已知）</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fanIn</span><span class="hljs-params">(chs ...<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">chan</span> <span class="hljs-title">string</span></span> &#123;<br>	c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)<br>	<span class="hljs-keyword">for</span> _, ch := <span class="hljs-keyword">range</span> chs &#123;<br>		<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(in <span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span></span> &#123;<br>			<span class="hljs-keyword">for</span> &#123;<br>				c &lt;- &lt;-in<br>			&#125;<br>		&#125;(ch)<br>	&#125;<br>	<span class="hljs-keyword">return</span> c<br>&#125;<br><br><span class="hljs-comment">// 方法二（适合已知数量）</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fanInBySelect</span><span class="hljs-params">(c1, c2 <span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">chan</span> <span class="hljs-title">string</span></span> &#123;<br>	c := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)<br>	<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>		<span class="hljs-keyword">for</span> &#123;<br>			<span class="hljs-keyword">select</span> &#123;<br>			<span class="hljs-keyword">case</span> m := &lt;-c1:<br>				c &lt;- m<br>			<span class="hljs-keyword">case</span> m := &lt;-c2:<br>				c &lt;- m<br>			&#125;<br>		&#125;<br>	&#125;()<br>	<span class="hljs-keyword">return</span> c<br>&#125;<br><br><span class="hljs-comment">// 非阻塞等待</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">nonBlockingWait</span><span class="hljs-params">(c <span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span> <span class="hljs-params">(<span class="hljs-keyword">string</span>, <span class="hljs-keyword">bool</span>)</span></span> &#123;<br>	<span class="hljs-keyword">select</span> &#123;<br>	<span class="hljs-keyword">case</span> m := &lt;-c:<br>		<span class="hljs-keyword">return</span> m, <span class="hljs-literal">true</span><br>	<span class="hljs-keyword">default</span>:<br>		<span class="hljs-keyword">return</span> <span class="hljs-string">&quot;&quot;</span>, <span class="hljs-literal">false</span><br><br>	&#125;<br>&#125;<br><br><span class="hljs-comment">// 超时机制</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">timeoutWait</span><span class="hljs-params">(c <span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>, timeout time.Duration)</span> <span class="hljs-params">(<span class="hljs-keyword">string</span>, <span class="hljs-keyword">bool</span>)</span></span> &#123;<br>	<span class="hljs-keyword">select</span> &#123;<br>	<span class="hljs-keyword">case</span> m := &lt;-c:<br>		<span class="hljs-keyword">return</span> m, <span class="hljs-literal">true</span><br>	<span class="hljs-keyword">case</span> &lt;-time.After(timeout):<br>		<span class="hljs-keyword">return</span> <span class="hljs-string">&quot;&quot;</span>, <span class="hljs-literal">false</span><br>	&#125;<br><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	<span class="hljs-comment">//m1 := msgGen(&quot;service1&quot;)</span><br>	<span class="hljs-comment">//m2 := msgGen(&quot;service2&quot;)</span><br>	<span class="hljs-comment">//for &#123;</span><br>	<span class="hljs-comment">//	fmt.Println(&lt;-m1)</span><br>	<span class="hljs-comment">//	if m, ok := nonBlockingWait(m2); ok &#123;</span><br>	<span class="hljs-comment">//		fmt.Println(m)</span><br>	<span class="hljs-comment">//	&#125; else &#123;</span><br>	<span class="hljs-comment">//		fmt.Println(&quot;no message from service2&quot;)</span><br>	<span class="hljs-comment">//	&#125;</span><br>	<span class="hljs-comment">//&#125;</span><br>	done := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">struct</span>&#123;&#125;)<br>	m1 := msgGen(<span class="hljs-string">&quot;service1&quot;</span>, done)<br>	<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++ &#123;<br>		<span class="hljs-keyword">if</span> m, ok := timeoutWait(m1, time.Second); ok &#123;<br>			fmt.Println(m)<br>		&#125; <span class="hljs-keyword">else</span> &#123;<br>			fmt.Println(<span class="hljs-string">&quot;timeout&quot;</span>)<br>		&#125;<br>	&#125;<br>	done &lt;- <span class="hljs-keyword">struct</span>&#123;&#125;&#123;&#125;<br>	&lt;-done<br>&#125;<br></code></pre></td></tr></table></figure>
<h1>8. 广度优先搜索算法（迷宫问题）</h1>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// maze.go</span><br><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;os&quot;</span><br>)<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">readMaze</span><span class="hljs-params">(filename <span class="hljs-keyword">string</span>)</span> [][]<span class="hljs-title">int</span></span> &#123;<br>	file, err := os.Open(filename)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(err)<br>	&#125;<br><br>	<span class="hljs-keyword">var</span> row, col <span class="hljs-keyword">int</span><br>	fmt.Fscanf(file, <span class="hljs-string">&quot;%d %d&quot;</span>, &amp;row, &amp;col)<br><br>	maze := <span class="hljs-built_in">make</span>([][]<span class="hljs-keyword">int</span>, row)<br>	<span class="hljs-keyword">for</span> i := <span class="hljs-keyword">range</span> maze &#123;<br>		maze[i] = <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">int</span>, col)<br>		<span class="hljs-keyword">for</span> j := <span class="hljs-keyword">range</span> maze[i] &#123;<br>			fmt.Fscanf(file, <span class="hljs-string">&quot;%d&quot;</span>, &amp;maze[i][j])<br>		&#125;<br>	&#125;<br><br>	<span class="hljs-keyword">return</span> maze<br>&#125;<br><br><span class="hljs-keyword">type</span> point <span class="hljs-keyword">struct</span> &#123;<br>	i, j <span class="hljs-keyword">int</span><br>&#125;<br><br><span class="hljs-keyword">var</span> dirs = [<span class="hljs-number">4</span>]point&#123;<br>	&#123;<span class="hljs-number">-1</span>, <span class="hljs-number">0</span>&#125;, &#123;<span class="hljs-number">0</span>, <span class="hljs-number">-1</span>&#125;, &#123;<span class="hljs-number">1</span>, <span class="hljs-number">0</span>&#125;, &#123;<span class="hljs-number">0</span>, <span class="hljs-number">1</span>&#125;,<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p point)</span> <span class="hljs-title">add</span><span class="hljs-params">(r point)</span> <span class="hljs-title">point</span></span> &#123;<br>	<span class="hljs-keyword">return</span> point&#123;p.i + r.i, p.j + r.j&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p point)</span> <span class="hljs-title">at</span><span class="hljs-params">(grid [][]<span class="hljs-keyword">int</span>)</span> <span class="hljs-params">(<span class="hljs-keyword">int</span>, <span class="hljs-keyword">bool</span>)</span></span> &#123;<br>	<span class="hljs-keyword">if</span> p.i &lt; <span class="hljs-number">0</span> || p.i &gt;= <span class="hljs-built_in">len</span>(grid) &#123;<br>		<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>, <span class="hljs-literal">false</span><br>	&#125;<br><br>	<span class="hljs-keyword">if</span> p.j &lt; <span class="hljs-number">0</span> || p.j &gt;= <span class="hljs-built_in">len</span>(grid[p.i]) &#123;<br>		<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>, <span class="hljs-literal">false</span><br>	&#125;<br>	<span class="hljs-keyword">return</span> grid[p.i][p.j], <span class="hljs-literal">true</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">walk</span><span class="hljs-params">(maze [][]<span class="hljs-keyword">int</span>, start, end point)</span> [][]<span class="hljs-title">int</span></span> &#123;<br>	steps := <span class="hljs-built_in">make</span>([][]<span class="hljs-keyword">int</span>, <span class="hljs-built_in">len</span>(maze))<br>	<span class="hljs-keyword">for</span> i := <span class="hljs-keyword">range</span> steps &#123;<br>		steps[i] = <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">int</span>, <span class="hljs-built_in">len</span>(maze[i]))<br>	&#125;<br><br>	Q := []point&#123;start&#125;<br><br>	<span class="hljs-keyword">for</span> <span class="hljs-built_in">len</span>(Q) &gt; <span class="hljs-number">0</span> &#123;<br>		cur := Q[<span class="hljs-number">0</span>]<br>		Q = Q[<span class="hljs-number">1</span>:]<br><br>		<span class="hljs-keyword">if</span> cur == end &#123;<br>			<span class="hljs-keyword">break</span><br>		&#125;<br><br>		<span class="hljs-keyword">for</span> _, dir := <span class="hljs-keyword">range</span> dirs &#123;<br>			next := cur.add(dir)<br><br>			<span class="hljs-comment">// maze at next is 0</span><br>			<span class="hljs-comment">// and steps at next is 0</span><br>			<span class="hljs-comment">// and next != start</span><br>			val, ok := next.at(maze)<br>			<span class="hljs-keyword">if</span> !ok || val == <span class="hljs-number">1</span> &#123;<br>				<span class="hljs-keyword">continue</span><br>			&#125;<br><br>			val, ok = next.at(steps)<br>			<span class="hljs-keyword">if</span> !ok || val != <span class="hljs-number">0</span> &#123;<br>				<span class="hljs-keyword">continue</span><br>			&#125;<br><br>			<span class="hljs-keyword">if</span> next == start &#123;<br>				<span class="hljs-keyword">continue</span><br>			&#125;<br><br>			curSteps, _ := cur.at(steps)<br>			steps[next.i][next.j] = curSteps + <span class="hljs-number">1</span><br><br>			Q = <span class="hljs-built_in">append</span>(Q, next)<br>		&#125;<br>	&#125;<br>	<span class="hljs-keyword">return</span> steps<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	maze := readMaze(<span class="hljs-string">&quot;maze/maze.in&quot;</span>)<br><br>	steps := walk(maze, point&#123;<span class="hljs-number">0</span>, <span class="hljs-number">0</span>&#125;,<br>		point&#123;<span class="hljs-built_in">len</span>(maze) - <span class="hljs-number">1</span>, <span class="hljs-built_in">len</span>(maze[<span class="hljs-number">0</span>]) - <span class="hljs-number">1</span>&#125;)<br><br>	<span class="hljs-keyword">for</span> _, row := <span class="hljs-keyword">range</span> steps &#123;<br>		<span class="hljs-keyword">for</span> _, val := <span class="hljs-keyword">range</span> row &#123;<br>			fmt.Printf(<span class="hljs-string">&quot;%3d&quot;</span>, val)<br>		&#125;<br>		fmt.Println()<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<h1>9. go 标准库</h1>
<h2 id="9-1-http标准库">9.1 http标准库</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211113120741480.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211113120741480">
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211113120755255.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211113120755255">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;fmt&quot;</span><br>	<span class="hljs-string">&quot;net/http&quot;</span><br>	<span class="hljs-string">&quot;net/http/httputil&quot;</span><br>)<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	request, err := http.NewRequest(http.MethodGet,<br>		<span class="hljs-string">&quot;http://www.imooc.com&quot;</span>, <span class="hljs-literal">nil</span>)<br>	request.Header.Add(<span class="hljs-string">&quot;User-Agent&quot;</span>,<br>		<span class="hljs-string">&quot;Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1&quot;</span>)<br><br>	client := http.Client&#123;<br>		CheckRedirect: <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(</span></span><br><span class="hljs-params"><span class="hljs-function">			req *http.Request,</span></span><br><span class="hljs-params"><span class="hljs-function">			via []*http.Request)</span> <span class="hljs-title">error</span></span> &#123;<br>			fmt.Println(<span class="hljs-string">&quot;Redirect:&quot;</span>, req)<br>			<span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span><br>		&#125;,<br>	&#125;<br><br>	resp, err := client.Do(request)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(err)<br>	&#125;<br>	<span class="hljs-keyword">defer</span> resp.Body.Close()<br><br>	s, err := httputil.DumpResponse(resp, <span class="hljs-literal">true</span>)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(err)<br>	&#125;<br><br>	fmt.Printf(<span class="hljs-string">&quot;%s\n&quot;</span>, s)<br>&#125;<br></code></pre></td></tr></table></figure>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211113131709575.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211113131709575">
<h2 id="9-2-json数据处理">9.2 json数据处理</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211113165314502.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211113165314502">
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;encoding/json&quot;</span><br>	<span class="hljs-string">&quot;fmt&quot;</span><br>)<br><br><span class="hljs-keyword">type</span> OrderItem <span class="hljs-keyword">struct</span> &#123; <span class="hljs-comment">// tag</span><br>	ID    <span class="hljs-keyword">string</span>  <span class="hljs-string">`json:&quot;id&quot;`</span><br>	Name  <span class="hljs-keyword">string</span>  <span class="hljs-string">`json:&quot;name&quot;`</span><br>	Price <span class="hljs-keyword">float64</span> <span class="hljs-string">`json:&quot;price&quot;`</span><br>&#125;<br><br><span class="hljs-keyword">type</span> Order <span class="hljs-keyword">struct</span> &#123;<br>	ID         <span class="hljs-keyword">string</span>      <span class="hljs-string">`json:&quot;id&quot;`</span><br>	TotalPrice <span class="hljs-keyword">float64</span>     <span class="hljs-string">`json:&quot;total_price&quot;`</span><br>	Items      []OrderItem <span class="hljs-string">`json:&quot;items&quot;`</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	unmarshal()<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">marshal</span><span class="hljs-params">()</span></span> &#123;<br>	o := Order&#123;<br>		ID:         <span class="hljs-string">&quot;1234&quot;</span>,<br>		TotalPrice: <span class="hljs-number">30</span>,<br>		Items: []OrderItem&#123;<br>			&#123;<br>				ID:    <span class="hljs-string">&quot;item_1&quot;</span>,<br>				Name:  <span class="hljs-string">&quot;learn go&quot;</span>,<br>				Price: <span class="hljs-number">15</span>,<br>			&#125;,<br>			&#123;<br>				ID:    <span class="hljs-string">&quot;item_2&quot;</span>,<br>				Name:  <span class="hljs-string">&quot;interview&quot;</span>,<br>				Price: <span class="hljs-number">10</span>,<br>			&#125;,<br>		&#125;,<br>	&#125;<br><br>	b, err := json.Marshal(o)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(err)<br>	&#125;<br><br>	fmt.Printf(<span class="hljs-string">&quot;%s\n&quot;</span>, b)<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">unmarshal</span><span class="hljs-params">()</span></span> &#123;<br>	s := <span class="hljs-string">`&#123;&quot;id&quot;:&quot;1234&quot;,&quot;total_price&quot;:30,&quot;items&quot;:[&#123;&quot;id&quot;:&quot;item_1&quot;,&quot;name&quot;:&quot;learn go&quot;,&quot;price&quot;:15&#125;,&#123;&quot;id&quot;:&quot;item_2&quot;,&quot;name&quot;:&quot;interview&quot;,&quot;price&quot;:10&#125;]&#125;`</span><br>	<span class="hljs-keyword">var</span> o Order<br>	err := json.Unmarshal([]<span class="hljs-keyword">byte</span>(s), &amp;o)<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(err)<br>	&#125;<br>	fmt.Printf(<span class="hljs-string">&quot;%+v\n&quot;</span>, o)<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="9-3-第三方API数据格式的解析">9.3 第三方API数据格式的解析</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">parseNLP</span><span class="hljs-params">()</span></span> &#123;<br>	res := <span class="hljs-string">`&#123;&quot;data&quot;: [</span><br><span class="hljs-string">	&#123;</span><br><span class="hljs-string">	&quot;synonym&quot;:&quot;&quot;,</span><br><span class="hljs-string">	&quot;weight&quot;:&quot;0.6&quot;,</span><br><span class="hljs-string">	&quot;word&quot;: &quot;真丝&quot;,</span><br><span class="hljs-string">	&quot;tag&quot;:&quot;材质&quot;</span><br><span class="hljs-string">	&#125;,</span><br><span class="hljs-string">	&#123;</span><br><span class="hljs-string">	&quot;synonym&quot;:&quot;&quot;,</span><br><span class="hljs-string">	&quot;weight&quot;:&quot;0.8&quot;,</span><br><span class="hljs-string">	&quot;word&quot;: &quot;韩都衣舍&quot;,</span><br><span class="hljs-string">	&quot;tag&quot;:&quot;品牌&quot;</span><br><span class="hljs-string">	&#125;,</span><br><span class="hljs-string">	&#123;</span><br><span class="hljs-string">	&quot;synonym&quot;:&quot;连身裙;联衣裙&quot;,</span><br><span class="hljs-string">	&quot;weight&quot;:&quot;1.0&quot;,</span><br><span class="hljs-string">	&quot;word&quot;: &quot;连衣裙&quot;,</span><br><span class="hljs-string">	&quot;tag&quot;:&quot;品类&quot;</span><br><span class="hljs-string">	&#125;</span><br><span class="hljs-string">	]</span><br><span class="hljs-string">&#125;`</span><br>	m := <span class="hljs-keyword">struct</span> &#123;<br>		Data []<span class="hljs-keyword">struct</span> &#123;<br>			Synonym <span class="hljs-keyword">string</span> <span class="hljs-string">`json:&quot;synonym&quot;`</span><br>			Tag     <span class="hljs-keyword">string</span> <span class="hljs-string">`json:&quot;tag&quot;`</span><br>		&#125; <span class="hljs-string">`json:&quot;data&quot;`</span><br>	&#125;&#123;&#125;<br>	json.Unmarshal([]<span class="hljs-keyword">byte</span>(res), &amp;m)<br>	fmt.Printf(<span class="hljs-string">&quot;%+v, %+v\n&quot;</span>,<br>		m.Data[<span class="hljs-number">2</span>].Synonym, m.Data[<span class="hljs-number">2</span>].Tag)<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="9-4-第三方http框架">9.4 第三方http框架</h2>
<img src="/crystal575/2021/11/13/golang%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/image-20211113165443902.png" srcset="/crystal575/img/loading.gif" lazyload class="" title="image-20211113165443902">
<h3 id="9-4-1-gin">9.4.1 gin</h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br>	<span class="hljs-string">&quot;math/rand&quot;</span><br>	<span class="hljs-string">&quot;time&quot;</span><br><br>	<span class="hljs-string">&quot;github.com/gin-gonic/gin&quot;</span><br>	<span class="hljs-string">&quot;go.uber.org/zap&quot;</span><br>)<br><br><span class="hljs-keyword">const</span> keyRequest = <span class="hljs-string">&quot;requestId&quot;</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br>	r := gin.Default()<br>	logger, err := zap.NewProduction()<br>	<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(err)<br>	&#125;<br><br>	<span class="hljs-comment">// middleware</span><br>	r.Use(<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(c *gin.Context)</span></span> &#123;<br>		s := time.Now()<br>		c.Next()<br><br>		<span class="hljs-comment">// path, response code, log latency</span><br>		logger.Info(<span class="hljs-string">&quot;incoming request&quot;</span>,<br>			zap.String(<span class="hljs-string">&quot;path&quot;</span>, c.Request.URL.Path),<br>			zap.Int(<span class="hljs-string">&quot;status&quot;</span>, c.Writer.Status()),<br>			zap.Duration(<span class="hljs-string">&quot;elapsed&quot;</span>, time.Now().Sub(s)))<br>	&#125;, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(c *gin.Context)</span></span> &#123;<br>		c.Set(keyRequest, rand.Int())<br><br>		c.Next()<br>	&#125;)<br><br>	r.GET(<span class="hljs-string">&quot;/ping&quot;</span>, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(c *gin.Context)</span></span> &#123;<br>		h := gin.H&#123;<br>			<span class="hljs-string">&quot;message&quot;</span>: <span class="hljs-string">&quot;pong&quot;</span>,<br>		&#125;<br>		<span class="hljs-keyword">if</span> rid, exists := c.Get(keyRequest); exists &#123;<br>			h[keyRequest] = rid<br>		&#125;<br>		c.JSON(<span class="hljs-number">200</span>, h)<br>	&#125;)<br>	r.GET(<span class="hljs-string">&quot;/hello&quot;</span>, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(c *gin.Context)</span></span> &#123;<br>		c.String(<span class="hljs-number">200</span>, <span class="hljs-string">&quot;hello&quot;</span>)<br>	&#125;)<br>	r.Run() <span class="hljs-comment">// listen and serve on 0.0.0.0:8080 (for windows &quot;localhost:8080&quot;)</span><br>&#125;<br></code></pre></td></tr></table></figure>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/crystal575/categories/golang/">golang</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/crystal575/tags/%E5%9F%BA%E7%A1%80-%E5%90%8E%E7%AB%AF/">基础 后端</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/crystal575/2021/11/13/golang%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">golanggolang基础知识</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/crystal575/2021/11/05/%E9%9D%A2%E7%BB%8F%E6%B1%87%E6%80%BB/">
                        <span class="hidden-mobile">后端开发面经</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        京ICP证123456号
      </a>
    </span>
    
      
        <span>
          <a
            href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
            rel="nofollow noopener"
            class="beian-police"
            target="_blank"
          >
            
              <span style="visibility: hidden; width: 0">|</span>
              <img src="/crystal575/img/police_beian.png" srcset="/crystal575/img/loading.gif" lazyload alt="police-icon"/>
            
            <span>京公网安备12345678号</span>
          </a>
        </span>
      
    
  </div>


  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" ></script>
<script  src="/crystal575/js/events.js" ></script>
<script  src="/crystal575/js/plugins.js" ></script>

<!-- Plugins -->


  
    <script  src="/crystal575/js/img-lazyload.js" ></script>
  



  



  <script  src="https://cdn.jsdelivr.net/npm/tocbot@4.12.3/dist/tocbot.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4.3.1/anchor.min.js" ></script>



  <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2.0.8/dist/clipboard.min.js" ></script>



  <script  src="/crystal575/js/local-search.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2.0.12/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/crystal575/js/boot.js" ></script>


</body>
</html>
